from typing import List
from fastapi import HTTPException, status, Depends
import json
from sqlalchemy.orm import Session
from table.role import Role
from common.custom_log import my_logger
from paramsModel.common import Page
from paramsModel.role import RoleParams
from common.response import CustomPageResponse, CustomApiResponse, response_code, responseCode


class RoleModel:
    @classmethod
    def get_list(cls, db: Session, page: Page, status: int = 0):
        role_total = cls.get_total_roles(db, status=status)
        if role_total == 0:
            return CustomPageResponse.pageBack(total=role_total)
        rolelist = db.query(Role).filter(Role.status == status).offset(page['start']).limit(page['pagesize']).all()
        return CustomPageResponse.pageBack(total=role_total, list=cls.formatterBackList(self=cls, queryList=rolelist),
                                           pagesize=page['pagesize'])

    # 获取用户的总数
    @classmethod
    def get_total_roles(cls, db: Session, status: int = 0):
        return db.query(Role).filter(Role.status == status).count()

    # 获取所有列表
    @classmethod
    def get_all(cls, db: Session, status: int = 0):
        rolelist = db.query(Role).filter(Role.status == status).all()
        return [{c.name: getattr(item, c.name) for c in Role.__table__.columns} for item in rolelist]

    # 获取所用觉得以及绝对底下对应的用户
    @classmethod
    def getRoleAndUsers(cls, db: Session, status: int = 0):
        rolelist = db.query(Role).filter(Role.status == status).all()
        cls.formatterBackList(self=cls, queryList=rolelist)

    # 格式化角色底下对应的用户
    def formatterBackList(self, queryList):
        back = []
        for item in queryList:
            back.append(dict(
                status=item.status,
                create_time=item.create_time,
                update_time=item.update_time,
                id=item.id,
                name=item.name,
                code=item.code,
                description=item.description,
                users=[{'name': child.user.name, 'id': child.user.id} for child in item.user_role]
            ))
        return back

    @classmethod
    def add(cls, addinfo: RoleParams, currentUser, db: Session):
        try:
            addinfo.model_dump(exclude_none=True)
            addinfo.updata_by_user_id = dict(currentUser).get('id')
            addinfo.code = str(addinfo.code).upper()
            data = {}
            for key in addinfo.__dict__:
                data[key] = getattr(addinfo, key)
            role = Role(**data)
            db.add(role)
            db.commit()
        except Exception as e:
            my_logger.error(f"发生错误: {e}")
            raise HTTPException(status_code=status.HTTP_200_OK, detail=CustomApiResponse(code=responseCode.Error.value, message='操作错误！').dict())

    @classmethod
    def dels(cls,db: Session,uids=[]):
        role_to_dels = db.query(Role).filter(Role.id.in_(uids)).all()
        for item in role_to_dels:
            item.status = 1
        db.commit()

    @classmethod
    def editByItem(cls,db: Session,item:dict = {}):
        db.query(Role).filter(Role.id == item.get('id')).update(item)
        db.commit()